<?php

namespace ticky;

class config {

    public static $config = [];

    // 加载配置文件
    public static function load($name) {
        $includeFile = self::config_file_path($name);
        $key = base64_encode($includeFile);
        if (!isset(self::$config[$key])) {
            self::$config[$key] = include $includeFile;
        }
        return self::$config[$key];
    }

    // 获取配置项
    public static function get($name, $key = null) {
        $config = self::load($name);
        if (is_array($config) && $key) {
            $value = isset($config[$key]) ? $config[$key] : "";
            return $value;
        }
        return $config;
    }

    // 获取所有配置信息
    public static function all() {
        return self::$config;
    }

    /**
     * 设置config文件
     * @param $config 配置信息
     *   config::set('app', ['default_m_layer' => 'bb']);
     */
    public static function set($name, $config) {
        $oldconfig = self::config_file_path($name);
        $pattern = $replacement = array();
        foreach ($config as $k => $v) {
            $pattern[$k] = "/'" . $k . "'\s*=>\s*([']?)[^']*([']?)(\s*),/is";
            $replacement[$k] = "'" . $k . "' => \${1}" . $v . "\${2}\${3},";
        }
        $str = file_get_contents($oldconfig);
        $str = preg_replace($pattern, $replacement, $str);
        return file_put_contents($oldconfig, $str, LOCK_EX);
    }

    //获取配置文件路径
    private static function config_file_path($name) {
        $config_path = defined('CONFIG_PATH') ? CONFIG_PATH : "";
        $config = APP_PATH . 'common' . DS . 'config';
        $ticky_config = TICKY_PATH . 'config';
        $model_name = defined('MODULE_NAME') ? MODULE_NAME : "";

        $configFile = [
            '0' => $name,
            '2' => $config_path . DS . $name . '.php',
            '3' => $config_path . DS . $name . '.php',
            //MODULE_PATH
            '4' => APP_PATH . $model_name . DS . 'config' . DS . $name . '.php',
            '6' => $config . DS . $name . '.php',
            '7' => $config . $name . '.php',
            '8' => $ticky_config . DS . $name . '.php',
        ];
        if (!is_file($name)) {
            foreach ($configFile as $x => $x_value) {
                //echo "Key=" . $x . ", Value=" . $x_value . '<br>';
                if (is_file($x_value)) {
                    $includeFile = $x_value;
                    break;
                }
            }
        } else {
            $includeFile = $name;
        }
        if (!is_file($includeFile)) {
            // implode('<br>', $configFile)
            app::fatalerror('config does not exist : ' . $name, $includeFile . '<br/><br/>' . implode('<br/>', $configFile), 1);
        }
        return $includeFile;
    }

}
